package cn.xfdzx.android.apps.shop.activity.myshop.bluedevic;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.luck.picture.lib.tools.ToastUtils;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import java.util.Set;

import cn.xfdzx.android.apps.shop.R;
import cn.xfdzx.android.apps.shop.activity.MainActivity;
import cn.xfdzx.android.apps.shop.activity.login.MobileLoginActivity;
import cn.xfdzx.android.apps.shop.adapter.BlueDevicListAdapter;
import cn.xfdzx.android.apps.shop.adapter.MyFollow_RetailAdapter;
import cn.xfdzx.android.apps.shop.adapter.MyFollow_XFDAdapter;
import cn.xfdzx.android.apps.shop.apps.Constants;
import cn.xfdzx.android.apps.shop.base.BaseMvpActivity;
import cn.xfdzx.android.apps.shop.bean.MyFollowBean;
import cn.xfdzx.android.apps.shop.contract.MyFollowContract;
import cn.xfdzx.android.apps.shop.presenter.MyFollowPresenter;
import cn.xfdzx.android.apps.shop.util.EmptyUtil;
import cn.xfdzx.android.apps.shop.util.ProgressDialog;
import cn.xfdzx.android.apps.shop.util.RegexUtil;
import cn.xfdzx.android.apps.shop.util.StatusBarUtil;
import cn.xfdzx.android.apps.shop.util.Utils;
import cn.xfdzx.android.apps.shop.util.UtilsData;
import cn.xfdzx.android.apps.shop.widget.SendPrintBlueDevicButton;
import cn.xfdzx.android.apps.shop.widget.SendSmsButton;

import static cn.xfdzx.android.apps.shop.activity.myshop.bluedevic.PrintSetActivity.EXTRA_DEVICE_NAME;

/*
/* 蓝牙打印机设置页面
 */
public class PrintBlueDevicSetActivity extends BaseMvpActivity<MyFollowPresenter> implements MyFollowContract.View, View.OnClickListener {
    private ImageView ivBack;      //标题栏-左边按钮
    private RelativeLayout.LayoutParams item_bar;
    private LinearLayout llState;
    // Member fields
    private BluetoothAdapter mBtAdapter;
    private String devicName;
    private TextView tv_name;
    private TextView tv_printtest;
    private TextView tv_collection;//连接状态


    // Member object for the services
    private BluetoothService mService = null;
    // Message types sent from the BluetoothService Handler
    public static final int MESSAGE_STATE_CHANGE = 1;
    public static final int MESSAGE_READ = 2;
    public static final int MESSAGE_WRITE = 3;
    public static final int MESSAGE_DEVICE_NAME = 4;
    public static final int MESSAGE_TOAST = 5;
    public static final int MESSAGE_CONNECTION_LOST = 6;
    public static final int MESSAGE_UNABLE_CONNECT = 7;

    // Key names received from the BluetoothService Handler
    public static final String DEVICE_NAME = "device_name";
    public static final String TOAST = "toast";
    private RelativeLayout rl_fenjian;
    private TextView tv_goods_addfenj,tv_goods_numfenj,tv_goods_minusfenj;//分拣联加减数量
    private TextView tv_goods_add,tv_goods_num,tv_goods_minus;//顾客联加减数量
    public static int printCustomerNum = 0;//打印顾客联数量
    public static int printFenJianNum = 1;//打印分拣联数量
    private SendPrintBlueDevicButton tvSendCode;//打印按钮
    private String storeType;

    @Override
    public int getLayoutId() {
        return R.layout.activity_bluetoothset;
    }

    private void initHigh() {
        item_bar = (RelativeLayout.LayoutParams) llState.getLayoutParams();
        item_bar.height = StatusBarUtil.getStatusBarHeight(this);
        llState.setLayoutParams(item_bar);

    }
    @Override
    public void initView() {
        devicName = getIntent().getStringExtra(EXTRA_DEVICE_NAME);
        mPresenter = new MyFollowPresenter();
        mPresenter.attachView(this);
        //获取店铺类型
        storeType = UtilsData.getPreference(this, "login").getString("storetype");
        llState = findViewById(R.id.ll_state);
        ivBack = findViewById(R.id.iv_back);
        tv_name = findViewById(R.id.tv_name);
        tv_printtest = findViewById(R.id.tv_printtest);
        tv_collection = findViewById(R.id.tv_collection);
        rl_fenjian = findViewById(R.id.rl_fenjian);

        tv_goods_addfenj = findViewById(R.id.tv_goods_addfenj);
        tv_goods_numfenj = findViewById(R.id.tv_goods_numfenj);
        tv_goods_minusfenj = findViewById(R.id.tv_goods_minusfenj);

        tv_goods_add = findViewById(R.id.tv_goods_add);
        tv_goods_num = findViewById(R.id.tv_goods_num);
        tv_goods_minus = findViewById(R.id.tv_goods_minus);
        tvSendCode = findViewById(R.id.tvSendCode);
        ivBack.setOnClickListener(this);
        tv_printtest.setOnClickListener(this);

        tv_goods_add.setOnClickListener(this);
        tv_goods_minus.setOnClickListener(this);
        tv_goods_addfenj.setOnClickListener(this);
        tv_goods_minusfenj.setOnClickListener(this);

        tv_name.setText(devicName);

        // 发送验证码倒计时监听.
        tvSendCode.setmListener(new SendPrintBlueDevicButton.SDSendValidateButtonListener() {
            @Override
            public void onClickSendValidateButton() {
                if (printCustomerNum==0&&printFenJianNum==0) {
                    ToastUtils.s(PrintBlueDevicSetActivity.this,"请选择打印联数");
                    return;
                }
                if (storeType.equals("0")) {
                    if (printCustomerNum==0) {
                        ToastUtils.s(PrintBlueDevicSetActivity.this,"请选择打印联数");
                        return;
                    }
                }else {
                    if (printFenJianNum==0) {
                        ToastUtils.s(PrintBlueDevicSetActivity.this,"请选择打印联数");
                        return;
                    }
                }

                tvSendCode.setmDisableTime(5);
                tvSendCode.startTickWork();
                bluetoothPrintTests();
            }

            @Override
            public void onTick() {
            }
        });

        initRecycle();
        initHigh();

        if (EmptyUtil.isNotEmpty(storeType)){
            if (storeType.equals("0")){
                printCustomerNum = 1;
                rl_fenjian.setVisibility(View.GONE);
            }else {
                printCustomerNum = 0;
                rl_fenjian.setVisibility(View.VISIBLE);
            }
        }

        initButtonState();
    }

    /*初始化加减按钮状态*/
    private void initButtonState() {
        tv_goods_num.setText(printCustomerNum+"");
        if (printCustomerNum <= 0){
            tv_goods_minus.setVisibility(View.GONE);
        }else {
            tv_goods_minus.setVisibility(View.VISIBLE);
        }

        if (printFenJianNum <= 0){
            tv_goods_minusfenj.setVisibility(View.GONE);
        }else {
            tv_goods_minusfenj.setVisibility(View.VISIBLE);
        }

    }

    private void initRecycle() {
        mService = BluetoothService.getInstance(this, mHandler);
        Log.e("mService",  mService.getState()+"-initRecycle");
      //  mService.setState(BluetoothService.STATE_CONNECTED);
//        mService = new BluetoothService(this, mHandler);
     }

    /****************************************************************************************************/
    @SuppressLint("HandlerLeak")
    private final Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MESSAGE_STATE_CHANGE:
                    switch (msg.arg1) {
                        case BluetoothService.STATE_CONNECTED://连接成功
                            Log.e("BluetoothService","连接成功---");

                            break;
                        case BluetoothService.STATE_CONNECTING://连接中
                            Log.e("BluetoothService","连接中");
                            break;
                        case BluetoothService.STATE_LISTEN:
                        case BluetoothService.STATE_NONE://未连接
                            Log.e("BluetoothService","未连接");
                            break;
                    }
                    break;
                case MESSAGE_WRITE:
                    Log.e("BluetoothService","MESSAGE_WRITE");
                    break;
                case MESSAGE_READ:
                    Log.e("BluetoothService","MESSAGE_READ");
                    break;
                case MESSAGE_DEVICE_NAME:
                    // save the connected device's name

                    break;
                case MESSAGE_TOAST:
                    Toast.makeText(getApplicationContext(),
                            msg.getData().getString(TOAST), Toast.LENGTH_SHORT)
                            .show();
                    break;
                case MESSAGE_CONNECTION_LOST:    //蓝牙已断开连接
                    Toast.makeText(getApplicationContext(), "蓝牙已断开连接",
                            Toast.LENGTH_SHORT).show();

                    tv_collection.setText("已断开");
                    break;
                case MESSAGE_UNABLE_CONNECT:     //无法连接设备
                    Toast.makeText(getApplicationContext(), "无法连接设备，请重启机器稍后再试",
                            Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };


    @Override
    protected void onResume() {
        super.onResume();
//        page = 1;
//        mPresenter.getFollowList(true,true,limit,page);
    }

    @Override
    public void finishRefresh() {
        //mRefreshLayout.finishRefresh(true);//刷新完成
    }

    @Override
    public void finishLoadMore() {
        //mRefreshLayout.finishLoadMore(true);//加载完成
    }

    @Override
    public void showLoading() {
        if (!ProgressDialog.getInstance().materialDialog.isShowing()) {
            ProgressDialog.getInstance().show(this);
        }
    }

    @Override
    public void hideLoading() {
        ProgressDialog.getInstance().dismiss();
    }

    @Override
    public void onError(Throwable throwable) {

    }

    @Override
    public void getFollowListSuccess(MyFollowBean bean) {
        if (bean.getStatus() == Constants.SUCCESS_CODE) {

        }else {
            Toast.makeText(this, bean.getMsg(), Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void getDeleteFollowSuccess(MyFollowBean bean) {
    }

    @Override
    protected void onDestroy() {

        // Make sure we're not doing discovery anymore
        if (mBtAdapter != null) {
            mBtAdapter.cancelDiscovery();
        }
        super.onDestroy();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_back:    //返回按钮点击
                finish();
                break;
            case R.id.tv_printtest:    //测试打印
                //bluetoothPrintTests();
                break;
            case R.id.tv_goods_add:    //顾客联+
                if (printCustomerNum>=5){
                    Toast.makeText(this, "顾客联最多可以打印5份哦", Toast.LENGTH_SHORT)
                            .show();
                    return;
                }
                printCustomerNum++;
                initButtonState();
                break;
            case R.id.tv_goods_minus:    //顾客联-
                printCustomerNum--;
                initButtonState();
                break;
            case R.id.tv_goods_addfenj:    //分拣联+
                if (printFenJianNum>=5){
                    Toast.makeText(this, "分拣联最多可以打印5份哦", Toast.LENGTH_SHORT)
                            .show();
                    return;
                }
                printFenJianNum++;
                initButtonState();
                break;
            case R.id.tv_goods_minusfenj:    //分拣联-
                printFenJianNum--;
                initButtonState();
                break;
        }
    }

    private void bluetoothPrintTests() {
        String msg = "当前时间2020-09-04 13:42:54\n送至-新发地掌鲜分拣中心\n***#3-1-1掌鲜***\n名酒城水果蔬菜新发地临时交易区\n--------------------------------\n下单时间:2020-09-03 08:00:00\n入库时间:\n商家电话:\n--------------------------------\n品名/规格                 价格\n--------------------------------\nL600小西瓜包甜 1          0.01  3-4斤3.00斤   \n--------------------------------\n总数量                       1\n总重量(斤)                   3\n--------------------------------\n送货地点：新发地百舸湾公司院内\n联系电话：18356036228\n备注：\n\n***完 新发地掌鲜***\n";
       // SendDataString(msg);
        if (printCustomerNum==1){
            createImage(msg);
        }else if (printCustomerNum>1){
            for (int i = 0; i < printCustomerNum; i++) {
                createImage(msg);
            }
        }

        if (!storeType.equals("0")) {
            if (printFenJianNum == 1){
                createImage(msg);
            }else if (printFenJianNum>1){
                for (int i = 0; i < printFenJianNum; i++) {
                    createImage(msg);
                }
            }
        }
    }

    private void SendDataString(String data) {

        if (mService.getState() != BluetoothService.STATE_CONNECTED) {
            Toast.makeText(this, "请连接蓝牙打印机", Toast.LENGTH_SHORT)
                    .show();
            return;
        }
        if (data.length() > 0) {
            try {
                mService.write(data.getBytes("GBK"));
            } catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                Toast.makeText(this, "打印机连接异常，打印失败", Toast.LENGTH_SHORT)
                        .show();
            }
        }
    }

    //QRcode
    private static final int QR_WIDTH = 350;
    private static final int QR_HEIGHT = 350;
    /*
     * 生成QR图
     */
    private void createImage(String testContent) {
        try {
            // 需要引入zxing包
            QRCodeWriter writer = new QRCodeWriter();

            String text = "https://www.xfdzx.cn/";

            if (text == null || "".equals(text) || text.length() < 1) {
                Toast.makeText(this, getText(R.string.empty), Toast.LENGTH_SHORT).show();
                return;
            }

            // 把输入的文本转为二维码
            BitMatrix martix = null;
            try {
                martix = writer.encode(text, BarcodeFormat.QR_CODE,
                        QR_WIDTH, QR_HEIGHT);
            } catch (WriterException e) {
                e.printStackTrace();
            }

            System.out.println("w:" + martix.getWidth() + "h:"
                    + martix.getHeight());

            Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>();
            hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
            BitMatrix bitMatrix = new QRCodeWriter().encode(text,
                    BarcodeFormat.QR_CODE, QR_WIDTH, QR_HEIGHT, hints);
            int[] pixels = new int[QR_WIDTH * QR_HEIGHT];
            for (int y = 0; y < QR_HEIGHT; y++) {
                for (int x = 0; x < QR_WIDTH; x++) {
                    if (bitMatrix.get(x, y)) {
                        pixels[y * QR_WIDTH + x] = 0xff000000;
                    } else {
                        pixels[y * QR_WIDTH + x] = 0xffffffff;
                    }

                }
            }

            Bitmap bitmap = Bitmap.createBitmap(QR_WIDTH, QR_HEIGHT,
                    Bitmap.Config.ARGB_8888);

            bitmap.setPixels(pixels, 0, QR_WIDTH, 0, 0, QR_WIDTH, QR_HEIGHT);

            byte[] data = PrintPicture.POS_PrintBMP(bitmap, 384, 0);
            String msg = "测试联!\n\n";
            SendDataByte(PrinterCommand.POS_Print_Text(msg, "GBK", 0, 1, 1, 0));
            SendDataByte(PrinterCommand.POS_Print_Text(testContent, "GBK", 0, 0, 0, 0));
            SendDataByte(data);
           // SendDataByte(PrinterCommand.POS_Set_PrtAndFeedPaper(30));
            SendDataByte(PrinterCommand.POS_Set_Cut(1));
            SendDataByte(PrinterCommand.POS_Set_PrtInit());
        } catch (WriterException e) {
            e.printStackTrace();
        }
    }

    /*
     *SendDataByte
     */
    private void SendDataByte(byte[] data) {

        if (mService.getState() != BluetoothService.STATE_CONNECTED) {
            Toast.makeText(this, "请连接蓝牙打印机", Toast.LENGTH_SHORT)
                    .show();
            return;
        }
        mService.write(data);
    }
}
